package com.example.springbootjackson.requestContext;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class RequestContext {

    private static final ThreadLocal<Map<String, Object>> THREAD_LOCAL;

    static {
        THREAD_LOCAL = new ThreadLocal<>();
    }

    /**
     * 用户idKey
     */
    public static final String USER_ID = "userId";

    /**
     * 设置数据
     *
     * @param key   键
     * @param value 值
     */
    public static void set(String key, Object value) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<>(8);
            THREAD_LOCAL.set(map);
        }
        map.put(key, value);
    }

    /**
     * 获取数据
     *
     * @param key 键
     * @return 值
     */
    public static Object get(String key) {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new HashMap<>(8);
            THREAD_LOCAL.set(map);
        }
        return map.get(key);
    }

    /**
     * 清除数据
     */
    public static void remove() {
        THREAD_LOCAL.remove();
    }

    public static Integer getUserId() {
        Object value = get(USER_ID);
        if (Objects.isNull(value)) {
            return null;
        }
        return Integer.valueOf(String.valueOf(value));
    }

    public static void setUserId(Integer userId) {
        set(USER_ID, userId);
    }
}
